//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package upgrade

import (
	"context"

	"atomgit.com/openlinksaas-org/api-server/dao"
	"atomgit.com/openlinksaas-org/api-server/dao/comment_dao"
	"atomgit.com/openlinksaas-org/api-server/dao/project_dao"
	"atomgit.com/openlinksaas-org/api-server/dao/project_entry_dao"
	"atomgit.com/openlinksaas-org/api-server/dao/watch_dao"
)

type UpToVer41 struct{}

func (up *UpToVer41) Exec(ctx context.Context) error {
	//清除关注中的所有board
	watchItemList, err := watch_dao.MyWatchDao.ListAllEntry(ctx)
	if err != nil {
		return err
	}
	for _, watchItem := range watchItemList {
		entryItem, err := project_entry_dao.EntryDao.Get(ctx, watchItem.TargetId, watchItem.ProjectId)
		if err != nil {
			continue
		}
		// ENTRY_TYPE_BOARD = 3;
		if entryItem.EntryType == 3 {
			err = watch_dao.MyWatchDao.Remove(ctx, watchItem.ProjectId, watchItem.UserId, watchItem.TargetId, watchItem.TargetType)
			if err != nil {
				continue
			}
		}
	}
	//清除评论中的所有board
	commentItemList, err := comment_dao.CommentDao.ListAllEntry(ctx)
	if err != nil {
		return err
	}
	for _, commentItem := range commentItemList {
		entryItem, err := project_entry_dao.EntryDao.Get(ctx, commentItem.TargetId, commentItem.ProjectId)
		if err != nil {
			continue
		}
		// ENTRY_TYPE_BOARD = 3;
		if entryItem.EntryType == 3 {
			err = comment_dao.CommentDao.Remove(ctx, commentItem.CommentId, commentItem.ProjectId, commentItem.TargetType, commentItem.TargetId)
			if err != nil {
				return err
			}
		}
	}
	//清除entry中的board入口
	err = project_entry_dao.EntryDao.RemoveAllBoard(ctx)
	if err != nil {
		return err
	}
	//清除回收站中的board
	err = project_dao.RecycleDao.RemoveAllBoard(ctx)
	if err != nil {
		return err
	}
	return dao.VersionDao.Set(ctx, dao.VERSION_KEY_SCHEMA, 41)
}
